package com.ctms.system.controller;

import com.ctms.common.utils.ShiroUtils;
import com.ctms.system.domain.*;
import com.ctms.system.service.CorrectsTaskService;
import com.ctms.system.service.ShiPinService;
import com.ctms.system.service.TaskReleaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
public class MyFileController {
    @Autowired
    private ShiPinService shiPinService;
    @Autowired
    TaskReleaseService taskReleaseService;
    @Autowired
    CorrectsTaskService correctsTaskService;

    private String  url;

    //增加时上传
    @RequestMapping(value="/uploadFile",produces="application/json;charset=UTF-8")
    @ResponseBody
    public String uploadFile(@RequestParam("fileName") MultipartFile[] files,@RequestParam("tid") Integer tid) {

        System.out.print("上传文件==="+"\n");
        //判断文件是否为空
        /*if (file.isEmpty()) {
            return "上传文件不可为空";
        }*/
        if (files.length<0){
            return "上传文件不可为空";
        }

        for (MultipartFile file :files) {

            // 获取文件名
            String fileName = file.getOriginalFilename();
//        System.out.print("上传的文件名为: "+fileName+"\n");

            fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + "_" + fileName;
            System.out.print("（加个时间戳，尽量避免文件名称重复）保存的文件名为: "+fileName+"\n");


            //加个时间戳，尽量避免文件名称重复
            String path = "C:/fileUpload/" +fileName;
            //String path = "E:/fileUpload/" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + "_" + fileName;
            //文件绝对路径
            System.out.print("保存文件绝对路径"+path+"\n");

            //创建文件路径
            File dest = new File(path);
            //判断文件是否已经存在
            if (dest.exists()) {
                return "文件已经存在";
            }

            //判断文件父目录是否存在
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdir();
            }

            try {
                //上传文件
                file.transferTo(dest); //保存文件
                System.out.print("保存文件路径"+path+"\n");
                //url="http://101.200.87.51/images/"+fileName;//正式项目
                url="http://localhost:8080/images/"+fileName;//本地运行项目
                int result= shiPinService.insertUrl(fileName,path,url);
                if (result>0){
                    if (tid == 0){
                        //增加
                        int id = taskReleaseService.selectMaxTid();
                        TaskReleaseDO taskReleaseDO = taskReleaseService.selectTaskByTid(id);
                        if (taskReleaseDO.getTaskFileUrl() == "" || taskReleaseDO.getTaskFileUrl() == null){
                            taskReleaseDO.setTaskFileUrl(fileName);
                            taskReleaseService.updateFileName(taskReleaseDO);
                        }else {
                            //增加文件名，逗号分隔
                            String name = taskReleaseDO.getTaskFileUrl();
                            taskReleaseDO.setTaskFileUrl(name+","+fileName);
                            taskReleaseService.updateFileName(taskReleaseDO);
                        }
                    }else {
                        //修改
                        int id = tid;
                        TaskReleaseDO taskReleaseDO = taskReleaseService.selectTaskByTid(id);
                        if (taskReleaseDO.getTaskFileUrl() == "" || taskReleaseDO.getTaskFileUrl() == null){
                            taskReleaseDO.setTaskFileUrl(fileName);
                            taskReleaseService.updateFileName(taskReleaseDO);
                        }else {
                            //增加文件名，逗号分隔
                            String name = taskReleaseDO.getTaskFileUrl();
                            taskReleaseDO.setTaskFileUrl(name+","+fileName);
                            taskReleaseService.updateFileName(taskReleaseDO);
                        }
                    }
                    System.out.println("修改文件名成功");
                }
                System.out.print("插入结果"+result+"\n");
                System.out.print("保存的完整url===="+url+"\n");

            } catch (IOException e) {
                return "上传失败";
            }
        }
        return "上传成功,文件url=="+url;
    }


    //学生提交作业时上传
    @RequestMapping(value="/commitFile",produces="application/json;charset=UTF-8")
    @ResponseBody
    public String commitFile(@RequestParam("fileName") MultipartFile[] files,@RequestParam("tid") Integer tid) {

        System.out.print("上传文件==="+"\n");
        //判断文件是否为空
       /* if (file.isEmpty()) {
            return "上传文件不可为空";
        }*/
        if (files.length<0){
            return "上传文件不可为空";
        }

        UserDO userDO= ShiroUtils.getUser();
        int userId = Integer.parseInt(Long.toString(userDO.getUserId()));
        //判断是否是第一次提交
        if (taskReleaseService.commitCount(tid,userId) == 0){
            /*CommitTaskDO commitTaskDO = taskReleaseService.selectByTidUserId(tid,userId);
            commitTaskDO.setTaskFileName("");*/
            //第一次提交
            for (MultipartFile file :files) {

                // 获取文件名
                String fileName = file.getOriginalFilename();
                // System.out.print("上传的文件名为: "+fileName+"\n");

                fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + "_" + fileName;
                System.out.print("（加个时间戳，尽量避免文件名称重复）保存的文件名为: "+fileName+"\n");


                //加个时间戳，尽量避免文件名称重复
                String path = "C:/fileUpload/" +fileName;
                //String path = "E:/fileUpload/" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + "_" + fileName;
                //文件绝对路径
                System.out.print("保存文件绝对路径"+path+"\n");

                //创建文件路径
                File dest = new File(path);

                //判断文件是否已经存在
                if (dest.exists()) {
                    return "文件已经存在";
                }

                //判断文件父目录是否存在
                if (!dest.getParentFile().exists()) {
                    dest.getParentFile().mkdir();
                }

                try {
                    //上传文件
                    file.transferTo(dest); //保存文件
                    System.out.print("保存文件路径"+path+"\n");
                    //url="http://你自己的域名/项目名/images/"+fileName;//正式项目
                    url="http://localhost:8080/images/"+fileName;//本地运行项目
                    int result= shiPinService.insertUrl(fileName,path,url);
                    if (result>0){
                        //UserDO userDO= ShiroUtils.getUser();
                        //int userId = Integer.parseInt(Long.toString(userDO.getUserId()));
                        //提交作业的最大id
                        int id = taskReleaseService.selectMaxCommit();
                        CommitTaskDO commitTaskDO = taskReleaseService.selectCommitFileById(id);
                        //增加打分表数据
                        CorrectsTaskDO correctsTaskDO = correctsTaskService.selectCorrectsTaskByTidUserId(tid,userId);
                        correctsTaskDO.setRemark(commitTaskDO.getRemark());
                        correctsTaskDO.setCommitTime(commitTaskDO.getCommitTime());
                        if (commitTaskDO.getTaskFileName() == "" || commitTaskDO.getTaskFileName() == null){
                            commitTaskDO.setTaskFileName(fileName);
                            taskReleaseService.updateCommitFile(commitTaskDO);
                            //增加打分表数据
                            correctsTaskDO.setTaskFileName(commitTaskDO.getTaskFileName());
                            correctsTaskService.updateCorrectsTask(correctsTaskDO);
                        }else {
                            String name = commitTaskDO.getTaskFileName();
                            commitTaskDO.setTaskFileName(name+","+fileName);
                            taskReleaseService.updateCommitFile(commitTaskDO);
                            //增加打分表数据
                            correctsTaskDO.setTaskFileName(commitTaskDO.getTaskFileName());
                            correctsTaskService.updateCorrectsTask(correctsTaskDO);
                        }

                        System.out.println("修改文件名成功");
                    }
                    System.out.print("插入结果"+result+"\n");
                    System.out.print("保存的完整url===="+url+"\n");

                } catch (IOException e) {
                    return "上传失败";
                }

            }
        }else {
            //不是第一次提交,先清除原文件
            CommitTaskDO commitTaskDO = taskReleaseService.selectByTidUserId(tid,userId);
            commitTaskDO.setTaskFileName("");
            String name="";

            //增加打分表数据
            CorrectsTaskDO correctsTaskDO = correctsTaskService.selectCorrectsTaskByTidUserId(tid,userId);
            correctsTaskDO.setRemark(commitTaskDO.getRemark());
            correctsTaskDO.setCommitTime(commitTaskDO.getCommitTime());
            for (MultipartFile file :files) {
                // 获取文件名
                String fileName = file.getOriginalFilename();
//        System.out.print("上传的文件名为: "+fileName+"\n");

                fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + "_" + fileName;
                System.out.print("（加个时间戳，尽量避免文件名称重复）保存的文件名为: "+fileName+"\n");


                //加个时间戳，尽量避免文件名称重复
                String path = "C:/fileUpload/" +fileName;
                //String path = "E:/fileUpload/" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + "_" + fileName;
                //文件绝对路径
                System.out.print("保存文件绝对路径"+path+"\n");

                //创建文件路径
                File dest = new File(path);

                //判断文件是否已经存在
                if (dest.exists()) {
                    return "文件已经存在";
                }

                //判断文件父目录是否存在
                if (!dest.getParentFile().exists()) {
                    dest.getParentFile().mkdir();
                }

                try {
                    //上传文件
                    file.transferTo(dest); //保存文件
                    System.out.print("保存文件路径"+path+"\n");
                    //url="http://你自己的域名/项目名/images/"+fileName;//正式项目
                    url="http://localhost:8080/images/"+fileName;//本地运行项目
                    int result= shiPinService.insertUrl(fileName,path,url);
                    if (result>0){
                        if (name == "" || name == null){
                            name = fileName;
                        }else {
                            name = name + "," + fileName;
                        }
                        System.out.println("修改文件名成功");
                    }
                    System.out.print("插入结果"+result+"\n");
                    System.out.print("保存的完整url===="+url+"\n");

                } catch (IOException e) {
                    return "上传失败";
                }
            }

            //循环完成，将文件插入
            commitTaskDO.setTaskFileName(name);
            taskReleaseService.updateCommitFile(commitTaskDO);

            correctsTaskDO.setTaskFileName(name);
            correctsTaskService.updateCorrectsTask(correctsTaskDO);
        }

        return "上传成功,文件url=="+url;
    }
    //查询
    @RequestMapping("/chaxun")
    public String huizhiDuanxin(Model model){
        System.out.print("查询视频"+"\n");
        List<ShipinDO> shipins=shiPinService.selectShipin();
        System.out.print("查询到的视频数量=="+shipins.size()+"\n");
        model.addAttribute("Shipins", shipins);

        return "/fileList";
    }

   /* @RequestMapping("/download")
    public void downLoad(String filePath, HttpServletResponse response, boolean isOnLine) throws Exception {
        File f = new File(filePath);
        if (!f.exists()) {
            response.sendError(404, "File not found!");
            return;
        }
        BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
        byte[] buf = new byte[1024];
        int len = 0;

        response.reset(); // 非常重要
        if (isOnLine) { // 在线打开方式
            URL u = new URL("file:///" + filePath);
            response.setContentType(u.openConnection().getContentType());
            response.setHeader("Content-Disposition", "inline; filename=" + f.getName());
            // 文件名应该编码成UTF-8
        } else { // 纯下载方式
            response.setContentType("application/x-msdownload");
            response.setHeader("Content-Disposition", "attachment; filename=" + f.getName());
        }
        OutputStream out = response.getOutputStream();
        while ((len = br.read(buf)) > 0)
            out.write(buf, 0, len);
        br.close();
        out.close();
    }
*/
}
